package com.ftg.learn.aop;

import com.ftg.learn.dto.LoginDto;
import com.ftg.learn.util.R;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 登陆日志
 * EnableAspectJAutoProxy(aspectj)
 *
 * @author 布衣
 */
@Slf4j
@Component
@Aspect
@EnableAspectJAutoProxy
public class LoginAop {

    @Resource
    HttpServletRequest request;

    @Resource
    JdbcTemplate jdbcTemplate;

    @Around("execution(public * com.ftg.learn.service.impl.AdminUserServiceImpl.login(..))")
    public R<Map<String, Object>> pointCut4(ProceedingJoinPoint joinpoint) {

        try {
            long start = System.currentTimeMillis();
            String sql = "insert into login_log(ipaddress,address,status,username,usetime) values(?,?,?,?,?)";
            LoginDto loginDto = (LoginDto) joinpoint.getArgs()[0];

            R<Map<String, Object>> obj = (R<Map<String, Object>>) joinpoint.proceed();
            long end = System.currentTimeMillis();
            int num = jdbcTemplate.update(sql,
                    request.getRemoteAddr(), request.getRequestURI(), obj.getCode() == 200 ? 0 : 1,
                    loginDto.getUsername(),end- start);
            log.info("登陆日志插入{}条数据", num);
            return obj;
        } catch (Throwable e) {
            return R.failure("登陆日志出错");
        }

    }

}
